import time
from config import *
from MCP23017 import send_command, send_data
from char import ROMUnOrderMap, DefaultRAMUnOrderMap
    
def clear_lcd():
    time.sleep(0.005)
    send_command(0x01) # Clear Screen

def init_lcd():
    try:
        send_command(0x33) # Must initialize to 8-line mode at first
        time.sleep(0.005)
        send_command(0x32) # Then initialize to 4-line mode
        time.sleep(0.005)
        send_command(0x28) # 2 Lines & 5*7 dots
        time.sleep(0.005)
        send_command(0x0C) # Enable display without cursor
        time.sleep(0.005)
        send_command(0x01) # Clear Screen
    except:
        return False
    else:
        return True
    
def print_lcd(x:int, y:int, string:str)->None:
    x = 0 if x<0 else 0x0F if x>0x0F else x
    y = 0 if y<0 else 0x01 if y>0x01 else y
    # 定位
    addr = 0x80 | 0x40 * y | x
    send_command(addr)
    # 写数据
    for char in string:
        o = ord(char)
        if char in DefaultRAMUnOrderMap:
            if DefaultRAMUnOrderMap["switch"]:
                raise Exception("Inject the data to ram first.")
            send_data(ord(char))
        elif o in ROMUnOrderMap:
            if isinstance(ROMUnOrderMap[o], list):
                send_data(ROMUnOrderMap[o][0])
                send_data(ROMUnOrderMap[o][1])
            else:
                send_data(ROMUnOrderMap[o])
        else:
            try:
                send_data(o)
            except:
                raise Exception("Design the char for %s." % char)
 
def scan_lcd()->int:
    data = bus.read_byte_data(MCP23017_ADDRESS, MCP23017_GPIOA) & READ_MASK
    # print(data)
    return 0 if data&1==0 else 1 if data&2==0 else 2 if data&4==0 else 3 if data&8==0 else 4 if data&16==0 else -1

def setColor(color:"red|green|blue|yellow|negenta|cyan|white")->None:
    global LIGHT_G, LIGHT_B, LIGHT_R
    LIGHT_G = 0x01
    LIGHT_B = 0x80
    LIGHT_R = 0x40
    LIGHT_R = 0
    if color=="red" or color=="yellow" or color=="negenta" or color=="white":
        LIGHT_R = 0
    if color=="green" or color=="yellow" or color=="cyan" or color=="white":
        LIGHT_G = 0
    if color=="blue" or color=="negenta" or color=="cyan" or color=="white":
        LIGHT_B = 0

color = ["red","green","blue","yellow","negenta","cyan","white"]

if __name__ == "__main__":
    init_lcd()
    print_lcd(0, 0, "Hello world!")
    """ 输入测试
    while True:
        print(scan_lcd())
        time.sleep(1)
    """
    """ 输出测试
    cnt = 0
    while True:
        setColor(color[cnt])
        print_lcd(0, 0, "Hello world!")
        cnt = (cnt+1)%7
        time.sleep(3)
    """